package net.suplementos.dao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import net.suplementos.exception.DAOException;

abstract class JPAAbstractDAO<Pojo extends Serializable, Id extends Serializable> {

    protected EntityManager manager;

    protected abstract Class<Pojo> doGetClass();

    protected JPAAbstractDAO(EntityManager manager) throws DAOException {
        this.manager = manager;
    }

    public void salvar(Pojo pojo) throws DAOException {
        try {
            manager.persist(pojo);
        } catch (Exception e) {
            throw new DAOException(e.getMessage(), e);
        }
    }

    public void alterar(Pojo pojo) throws DAOException {
        try {
            manager.persist(pojo);
        } catch (Exception e) {
            throw new DAOException(e.getMessage(), e);
        }
    }

    public void excluir(Pojo pojo) throws DAOException {
        try {
            manager.remove(pojo);
        } catch (Exception e) {
            throw new DAOException(e.getMessage(), e);
        }
    }

    @SuppressWarnings("unchecked")
    public List<Pojo> listarTodos() throws DAOException {
        try {
            String query = "select p from " + doGetClass().getCanonicalName() + " p";

            return manager.createQuery(query).getResultList();
        } catch (Exception e) {
            throw new DAOException(e.getMessage(), e);
        }
    }

    public Pojo get(Id id) throws DAOException {
        try {
            return manager.find(doGetClass(), id);
        } catch (Exception e) {
            throw new DAOException(e.getMessage(), e);
        }
    }

    @SuppressWarnings("unchecked")
    protected List<Pojo> consultar(String consulta) throws DAOException {
        try {
            Query query = manager.createQuery(consulta);

            return query.getResultList();
        } catch (Exception e) {
            throw new DAOException(e.getMessage(), e);
        }
    }

    @SuppressWarnings("unchecked")
    protected List<Pojo> consultar(String consulta, Object param) throws DAOException {
        try {
            Query query = manager.createQuery(consulta);

            query.setParameter(1, param);

            return query.getResultList();
        } catch (Exception e) {
            throw new DAOException(e.getMessage(), e);
        }
    }

    @SuppressWarnings("unchecked")
    protected List<Pojo> consultar(String consulta, Object[] param) throws DAOException {
        try {
            Query query = manager.createQuery(consulta);
            int cont = 1;

            for (Object parametro : param) {
                query.setParameter(cont++, parametro);
            }

            return query.getResultList();
        } catch (Exception e) {
            throw new DAOException(e.getMessage(), e);
        }
    }
}
